﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;

using SmartQuant;

namespace LiuLin.OQ2014.Extension
{
    public class PositionHelper
    {

        Strategy strategy;

        public PositionHelper(Strategy stg)
        {
            strategy = stg;
        }

        #region 加载策略持仓
        /// <summary>
        /// 保存持仓
        /// </summary>
        public void Load()
        {
            if (strategy.Mode == StrategyMode.Live)
            {
                foreach (Instrument inst in strategy.Instruments)
                {
                    loadOne(inst.Symbol);
                }
            }
        }

        /// <summary>
        /// 保存一条持仓
        /// </summary>
        /// <param name="symbol">合约代码</param>
        /// <returns></returns>
        void loadOne(string symbol)
        {
            int amount;
            double price;
            DateTime dateTime;

            //获取路径
            string filePath = Environment.CurrentDirectory + @"\Positions\" + strategy.ToString() + @".xml";
            string xPath = @"/Positions/" + symbol;

            //读取持仓
            try
            {
                string strAmount = XMLHelper.GetXmlNodeByXpath(filePath, xPath + @"/Amount").InnerText;
                amount = Convert.ToInt32(strAmount);
            }
            catch (Exception e)
            {
                amount = 0;
            }

            //读取价格
            try
            {
                string strPrice = XMLHelper.GetXmlNodeByXpath(filePath, xPath + @"/Price").InnerText;
                price = Convert.ToDouble(strPrice);
            }
            catch (Exception e)
            {
                price = 0;
            }

            //读取时间
            try
            {
                string strDateTime = XMLHelper.GetXmlNodeByXpath(filePath, xPath + @"/DateTime").InnerText; 
                dateTime = DateTime.Parse(strDateTime);
            }
            catch(Exception e)
            {
                dateTime = DateTime.Now;
            }


            //如果启动策略时持仓不为0，多半是没退出oq重启的策略，此时选择不加载。
            foreach(Position pos in strategy.Portfolio.Positions)
            {
                if(pos.Instrument.Symbol == symbol && pos.Amount != 0)
                {
                    return;
                }
            }

            if(amount > 0)
            {
                strategy.Portfolio.Add(new Fill(dateTime, new Order(), strategy.InstrumentManager.Get(symbol), CurrencyId.CNY, SmartQuant.OrderSide.Buy, amount, price, "xml文件导入"));
            }
            else if(amount < 0)
            {
                strategy.Portfolio.Add(new Fill(dateTime, new Order(), strategy.InstrumentManager.Get(symbol), CurrencyId.CNY, SmartQuant.OrderSide.Sell, -amount, price, "xml文件导入"));

            }

        }

        #endregion


        #region 保存策略持仓

        /// <summary>
        /// 保存持仓
        /// </summary>
        public void Save()
        {
            if (strategy.Mode == StrategyMode.Live)
            {
                foreach (Instrument inst in strategy.Instruments)
                {
                    saveOne(inst.Symbol);
                }
            }
        }

        /// <summary>
        /// 保存一条持仓
        /// </summary>
        /// <param name="symbol"></param>
        public void Save(string symbol)
        {
            if (strategy.Mode == StrategyMode.Live)
            {
                saveOne(symbol);
            }
        }

        /// <summary>
        /// 保存一条持仓
        /// </summary>
        /// <param name="symbol">合约</param>
        public void saveOne(string symbol)
        {

            string strAmount;
            string strPrice;
            string strDateTime;
            Position position;

            foreach(Position pos in strategy.Portfolio.Positions)
            {
                if(pos.Instrument.Symbol == symbol)
                {
                    position = pos;
                }

                //获取路径
                string directoryPath = Environment.CurrentDirectory + @"\Positions";
                string filePath = directoryPath + @"\" + strategy.ToString() + @".xml";
                string xPath = @"/Positions/" + symbol;

                //为空要删除
                if(pos == null || pos.Amount ==0)
                {
                    try
                    {
                        XMLHelper.DeleteXmlNodeByXPath(filePath, xPath);
                    }
                    catch (Exception e)
                    {
                        LogHelper.Error(e.Message);
                    }
                }
                else
                {
                    //获取持仓信息
                    strAmount = pos.Amount.ToString();
                    strPrice = pos.Price.ToString();
                    strDateTime = DateTime.Now.ToString();

                    //创建目录、文件、节点
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    if (!File.Exists(filePath))
                    {
                        XMLHelper.CreateXmlDocument(filePath, "Positions", "1.0", "utf-8", null);
                    }
                    if (XMLHelper.GetXmlNodeByXpath(filePath, xPath) == null)
                    {
                        XMLHelper.CreateXmlNodeByXPath(filePath, @"/Positions", symbol, "", "", "");
                    }

                    //保存持仓
                    XMLHelper.CreateOrUpdateXmlNodeByXPath(filePath, xPath, "Amount", strAmount);

                    //保存价格
                    XMLHelper.CreateOrUpdateXmlNodeByXPath(filePath, xPath, "Price", strPrice);

                    //保存时间
                    XMLHelper.CreateOrUpdateXmlNodeByXPath(filePath, xPath, "DateTime", strDateTime);
                }
            }
        }

        #endregion
    }
}
